package com.luobr.backend.api.imageSearch.sub;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONUtil;
import com.luobr.backend.common.ResponseCode;
import com.luobr.backend.exception.BusinessException;
import com.luobr.backend.exception.ThrowUtils;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 以图搜图第一步
 *
 * 通过向百度发送 POST请求，获取给定图片 URL的相似图片页面地址
 */
@Slf4j
public class GetImagePageUrlApi {

    /**
     * 上传图片地址并返回百度缩图之后的地址
     *
     * @param imageUrl 图片路径
     * @return 以图搜图的页面地址
     */
    public static String getImagePageUrl(String imageUrl) {
        // 1. 准备请求参数
        Map<String, Object> formData = new HashMap<>();
        formData.put("image", imageUrl);
        formData.put("tn", "pc");
        formData.put("from", "pc");
        formData.put("image_source", "PC_UPLOAD_URL");

        // 获取当前时间戳
        long uptime = System.currentTimeMillis();
        // 请求地址
        String url = "https://graph.baidu.com/upload?uptime=" + uptime;

        try {
            // 2. 发送 POST 请求到百度接口
            HttpResponse response = HttpRequest.post(url)
                    // 这里需要指定acs-token 不然会响应系统异常
                    .header("acs-token", RandomUtil.randomString(1))
                    .form(formData)
                    .timeout(5000)
                    .execute();
            // 判断响应状态
            ThrowUtils.throwIf(HttpStatus.HTTP_OK != response.getStatus(),
                    ResponseCode.OPERATION_ERROR, "接口调用失败");
            // 解析响应
            String responseBody = response.body();
            Map<String, Object> result = JSONUtil.toBean(responseBody, Map.class);

            // 3. 处理响应结果
            ThrowUtils.throwIf(result == null || !Integer.valueOf(0).equals(result.get("status")),
                    ResponseCode.OPERATION_ERROR, "接口调用失败");
            Map<String, Object> data = (Map<String, Object>) result.get("data");
            String rawUrl = (String) data.get("url");
            // 对 URL 进行解码
            String searchResultUrl = URLUtil.decode(rawUrl, StandardCharsets.UTF_8);
            // 如果 URL 为空
            ThrowUtils.throwIf(searchResultUrl == null , ResponseCode.OPERATION_ERROR, "未返回有效结果");
            return searchResultUrl;
        } catch (Exception e) {
            log.error("搜索失败", e);
            throw new BusinessException(ResponseCode.OPERATION_ERROR, "搜索失败");
        }
    }
}